import 'dart:async';
import 'dart:io';
import 'dart:isolate';

void main() {
  TestIsolate().init();
}

class TestIsolate {
  ReceivePort receivePort1 = ReceivePort();
  Isolate? isolate;
  SendPort? sendPort2;

  void init() async {
    receivePort1.listen((message) {
      if (message is SendPort) {
        sendPort2 = message;
      } else {
        print("time1:" + message.toString());
      }
    });
    isolate = await Isolate.spawn(eat, receivePort1.sendPort);
    Future.delayed(const Duration(seconds: 2), () {
      print("终止isolate:" + (isolate != null ? true : false).toString());
      isolate?.kill();
      print("终止isolate success !! ");
    });
  }
}

void eat(SendPort sendPort1) {
  ReceivePort receivePort2 = ReceivePort();
  receivePort2.listen((message) {});
  sendPort1.send(receivePort2.sendPort);
  while (true) {
    sleep(const Duration(milliseconds: 500));
    print("time2:" + DateTime.now().millisecondsSinceEpoch.toString());
    sendPort1.send(DateTime.now().millisecondsSinceEpoch.toString());
  }
}
